// pages/xianwangdian/xianwangdian.js

const app = getApp();

import {
  hexMD5
} from "../../utils/md5.js"


// import {
//   hexMD5
// } from "./utils/md5.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ycquyu: true,
    quyu: '',
    page: Number, // 起始页码
    videlist: [],

    openid: '',
    jiami: '',
    OPEN_ID: '',
    session_key: '',

    userlatitude: '', //纬度
    userlongitude: '', //经度
    valuea: '',

    shiqu: [{
        shiji: '西安'
      },
      {
        shiji: '咸阳'
      },
      {
        shiji: '汉中'
      },
      {
        shiji: '安康'
      },
      {
        shiji: '延安'
      },
      {
        shiji: '渭南'
      },
      {
        shiji: '铜川'
      },
      {
        shiji: '宝鸡'
      },
      {
        shiji: '榆林'
      },
      {
        shiji: '商洛'
      },
    ],


  },

  tiaoruzhu() {

    wx.navigateTo({
      url: '../../pages/shzc/shzc',
    })
  },

  chuqu() {
    this.setData({
      ycquyu: false,


    })


  },

  quyuxinxi(e) {
    console.log(e.currentTarget.dataset.item.shiji);
    this.setData({
      ycquyu: true,
      quyu: e.currentTarget.dataset.item.shiji,

    })
    this.getvidelist()
  },



  getvidelist(n = '') {
    wx.showLoading({
      title: '加载中...',
    })





    this.setData({
      openid: app.globalData.openid,
      jiami: app.globalData.jiami,
      OPEN_ID: app.globalData.openid,
      session_key: app.globalData.session_key,
    })



    console.log(this.data.jiami);
    console.log(this.data.openid);
    console.log(this.data.OPEN_ID);
    console.log(this.data.session_key);


    wx.request({
      url: app.globalData.interface+'/squareDance/API_5301_shanxiShanghuList',
      method: 'POST',
      data: {
        KeyWord: n,
        currentPage: '', //当前页   非必填
        CITY: this.data.quyu,
        OPEN_ID: this.data.openid, //用户OPEN_ID
        session_key: this.data.session_key,
        OPEN_UUID: this.data.jiami
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        console.log('res', res);
        console.log('res', res.data.result);
        wx.hideLoading()
        if (res.data.result == 'success' && res.data.data.length != 0) {
          console.log('翻页', res.data.data[0].page.totalPage);

          const copypage = JSON.stringify(res.data.data[0].page.totalPage)
          const totalPage = JSON.parse(copypage)
          console.log('totalPage', totalPage);

          console.log(res.data.data, );



          const liscop = res.data.data.map((item) => {
            console.log(this.data.userlatitude);
            console.log(this.data.userlongitude);
            console.log(item.DIMENSION);
            console.log(item.LONGITUDE);
            return {
              ...item,
              DISTANCE: this.getDistance(this.data.userlatitude, this.data.userlongitude, item.DIMENSION, item.LONGITUDE)
            }


          })

          console.log(liscop);


          this.setData({
            videlist: liscop,
            totalPage: totalPage
          })



          console.log('最大页码数', this.data.totalPage);

          // this.findXy()



        } else {
          wx.showModal({
            title: "暂无该条数据",
            content: '请重新输入关键词',
            showCancel: false,
          });
        }
      },
      fail: (res => {
        wx.hideLoading()
      })
    })


  },


  clear() {
    console.log(232);
    console.log('最大页码', this.data.totalPage);
    this.setData({
      page: 1,
      videlist: []
    })
    setTimeout(() => {
      this.getvidelist()
    }, 500);
  },

  onchange() {
    console.log(this.data.valuea);
    // const value = this.data.valuea
    // if (value == '') {
    //   console.log('8585', this.data.page);
    //   this.setData({
    //     page: 1, // 起始页码
    //     videlist: [],
    //   })
    //   setTimeout(() => {
    //     this.getvidelist()
    //   }, 500);

    // }else{
    const n = this.data.valuea
    this.getvidelist(n)
    // }
  },

  watchPassWord(e) {
    console.log(e.detail.value);
    if (e.detail.value == '') {
      console.log('8585', this.data.page);
      this.setData({
        page: 1, // 起始页码
        videlist: [],
      })
      setTimeout(() => {
        this.getvidelist()
      }, 500);
    }
  },









  Rad: function (d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },

  getDistance: function (lat1, lng1, lat2, lng2) {
    // lat1用户的纬度
    // lng1用户的经度
    // lat2商家的纬度
    // lng2商家的经度
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    // s = s.toFixed(2) + '公里' //保留两位小数
    s = s.toFixed(2) //保留两位小数
    console.log('经纬度计算的距离:' + s)
    return s
  },




  // quditu(e) {

  //   console.log(e);
  //   console.log(e.currentTarget.dataset.item.DIMENSION);
  //   console.log(e.currentTarget.dataset.item.LONGITUDE);
  //   console.log(e.currentTarget.dataset.item.EMPLOYEE_ADD);
  //   console.log(e.currentTarget.dataset.item.L4name);

  //   if (e.currentTarget.dataset.item.DIMENSION != '') {

  //     wx.openLocation({
  //       longitude: Number(e.currentTarget.dataset.item.LONGITUDE),
  //       latitude: Number(e.currentTarget.dataset.item.DIMENSION),
  //       name: e.currentTarget.dataset.item.L4name,
  //       address: e.currentTarget.dataset.item.EMPLOYEE_ADD
  //     })
  //   }
  // },



  quditu(e) {



    if (this.data.userlongitude != '') {
      wx.openLocation({
        // longitude: Number(this.data.longitude),
        // latitude: Number(this.data.latitude),
        longitude: this.data.userlongitude,
        latitude: this.data.userlatitude,
        name: '当前位置',
        address: '地图信息',
      })
    }
  },


  tiaoxiangqin(e) {

    console.log(e.currentTarget.dataset.item);
    console.log(e.currentTarget.dataset);
    var info = {
      BRANCHES: e.currentTarget.dataset.item.BRANCHES,
      MERCHANT_BUSSINESS: e.currentTarget.dataset.item.MERCHANT_BUSSINESS,
      MERCHANT_CHECK: e.currentTarget.dataset.item.MERCHANT_CHECK,
      MERCHANT_HEAD: e.currentTarget.dataset.item.MERCHANT_HEAD,
      SHANGHU_NAME: e.currentTarget.dataset.item.SHANGHU_NAME,
      SHANGHU_ADD: e.currentTarget.dataset.item.SHANGHU_ADD,
      SHANGHU_PHONE: e.currentTarget.dataset.item.SHANGHU_PHONE,
      DISTRICT: e.currentTarget.dataset.item.DISTRICT,
      SHANGHU_TYPE: e.currentTarget.dataset.item.SHANGHU_TYPE,
    }


    const infocopy = JSON.stringify(info)

    wx.navigateTo({
      url: `/pages/shanxishangquanxiangqing/shanxishangquanxiangqing?liuziniuda=${infocopy}`,
    })

  },



  huosna() {


    var that = this
    wx.login({
      success: function (res) {
        console.log(res);
        if (res.code) { //wx.login获取code。
          console.log(res.code);
          //发起网络请求
          wx.request({
            url: app.globalData.interface+'/post/API_1062_appGetOpenid',
            method: 'GET',
            //向后端发送的数据
            data: {
              code: res.code //将code发送到后台服务器。
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
            },
            success: res => {
              console.log(res);
              console.log(res.data.openid);

              that.setData({
                openid: res.data.openid,
                OPEN_ID: res.data.openid,
                session_key: res.data.session_key,
                jiami: hexMD5(`${res.data.openid.substring(0,20)}${res.data.session_key.substring(0,10)}`),
              })
              // that.scanCod()
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.findXy()
    let that = this

    console.log(app.globalData.openid);
    that.setData({
      openid: app.globalData.openid,
      jiami: app.globalData.jiami,
      OPEN_ID: app.globalData.openid,
      session_key: app.globalData.session_key,
    })

    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res);
        console.log(res.latitude);
        console.log(res.longitude);

        that.setData({
          userlatitude: res.latitude,
          userlongitude: res.longitude
        })

        // _this.getDistance(res.latitude, res.longitude, item.DIMENSION, item.LONGITUDE)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    //查询用户与商家的距离

    this.setData({
      page: 1, // 起始页码
    })
    let that = this

    if (app.globalData.openid == '' || app.globalData.session_key == '') {

      that.huosna()

      setTimeout(() => {
        that.getvidelist()
      }, 1000);
    } else {

      setTimeout(() => {
        that.getvidelist()
      }, 1000);

    }






  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let totalP = this.data.totalPage //最大页码数
    const that = this
    let page = that.data.page + 1 // 当前页码+1，获取下一页的数据
    console.log('page', page);

    if (page <= totalP && totalP > 1) {
      that.setData({
        page: page,
      })
      wx.request({
        url: app.globalData.interface+'/squareDance/API_5301_shanxiShanghuList',
        method: 'POST',
        data: {

          currentPage: page, //当前页   非必填
          CITY: this.data.quyu,
          OPEN_ID: this.data.openid, //用户OPEN_ID
          session_key: this.data.session_key,
          OPEN_UUID: this.data.jiami
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          console.log('res', res);
          console.log('res', res.data.result);

          if (res.data.result == 'success') {


            const liscop = res.data.data.map((item) => {
              console.log(this.data.userlatitude);
              console.log(this.data.userlongitude);
              console.log(item.DIMENSION);
              console.log(item.LONGITUDE);
              return {
                ...item,
                DISTANCE: this.getDistance(this.data.userlatitude, this.data.userlongitude, item.DIMENSION, item.LONGITUDE)
              }


            })


            console.log(liscop);

            that.setData({
              videlist: [...that.data.videlist, ...liscop], //es6中的在旧数据中加其他数据,
            })

            // that.findXy()

            wx.hideLoading()
            console.log('最大页码数', this.data.totalPage);
            wx.showToast({
              title: '数据请求成功',
              icon: 'success',
              duration: 1000,
            })

          }
        },
        fail: (res => {
          wx.hideLoading()
        })
      })
      console.log("56565656", this.data.page);

    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'error',
        duration: 1500,
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})